package com.czkt.springboot_mybatis_test.config;

import com.czkt.springboot_mybatis_test.entity.SysUser;
import com.czkt.springboot_mybatis_test.entity.vo.UserRole;
import com.czkt.springboot_mybatis_test.service.ISysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private ISysUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        System.out.println("调用MyShiroRealm.doGetAuthenticationInfo获取权限信息！");
//        //获取权限信息
//        SysUser sysUser = (SysUser) principalCollection.getPrimaryPrincipal();
//        return new SimpleAuthorizationInfo();
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获得身份信息
//        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        String usrName = (String) authenticationToken.getPrincipal();
        UserRole sysUser = userService.selectRoleUser(usrName);
        if(sysUser == null){
            throw new UnknownAccountException();//账号错误
        }
        if (sysUser.getUsrFlag()==null || sysUser.getUsrFlag() == 0){
            throw new LockedAccountException();//账号锁定
        }
        //身份(根据用户名查询数据库获得的用户)  凭证(查询数据库获得的密码)  Realm对象的名称
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser,sysUser.getUsrPassword(),getName());
        //返回身份信息
        return info;
    }
}
